package com.gitee.wsl.doc.prosemirror.history.ropesequence

class Leaf<T>(val values: List<T>) : RopeSequence<T>() {

    override val length: Int
        get() = values.size

    override val depth: Int
        get() = 0

    override fun flatten(): List<T> {
        return this.values
    }

    override fun sliceInner(from: Int, to: Int): Leaf<T> {
        if (from == 0 && to == this.length) return this
        return Leaf(this.values.slice(from until to))
    }

    override fun getInner(i: Int): T {
        return this.values[i]
    }

    override fun forEachInner(from: Int, to: Int, start: Int, f: (T, Int) -> Boolean): Boolean {
        for (i in from until to) {
            if (!f(values[i], start + i)) return false
        }
        return true
    }

    override fun forEachInvertedInner(from: Int, to: Int, start: Int, f: (T, Int) -> Boolean): Boolean {
        for (i in from - 1 downTo to) {
            if (!f(values[i], start + i)) return false
        }
        return true
    }

    override fun leafAppend(other: RopeSequence<T>): Leaf<T>? {
        return if (this.length + other.length <= GOOD_LEAF_SIZE) {
            Leaf(this.values + other.flatten())
        } else {
            null
        }
    }

    override fun leafPrepend(other: RopeSequence<T>): Leaf<T>? {
        return if (this.length + other.length <= GOOD_LEAF_SIZE) {
            Leaf(other.flatten() + this.values)
        } else {
            null
        }
    }

    override fun toString(): String {
        return "Leaf {values: $values, lenght: $length, depth: $depth}"
    }
}